//
//  SHDetViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/10/16.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "SHDetViewController.h"

#import "SHView.h"
#import "RigisterView.h"
@interface SHDetViewController ()<UIPickerViewDelegate,UIPickerViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
    SHView *shview;
    UIView *bottomView;
    UIImagePickerController *imagepc;
    RigisterView *riView;
}

@property (nonatomic,strong)UIPickerView *pickerView;

@property (nonatomic,copy)NSString *fyPrice;

@property (nonatomic, strong) NSMutableArray *regionArray;

@property (nonatomic, assign) NSInteger provinceIndex,cityIndex,districtIndex;

@property (nonatomic,copy)NSString *imgState;

@property (nonatomic,copy)NSString *imgUrl1;
@property (nonatomic,copy)NSString *imgUrl2;
@property (nonatomic,copy)NSString *imgUrl3;
@property (nonatomic,copy)NSString *imgUrl4;

@property (nonatomic,copy)NSString *orderNum;

@end

@implementation SHDetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setBGColor];
    [self showNav:@"上户"];
    [self loadUI];
    [self loadNum];
    self.provinceIndex = self.cityIndex = self.districtIndex = 0;
    //
    NSString * path = [[NSBundle mainBundle] pathForResource:@"Province" ofType:@"plist"];
    self.regionArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
    
}

- (void)loadUI{
    UIScrollView *sclview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    sclview.contentSize = CGSizeMake(ScreenWidth, 720);
    [self.view addSubview:sclview];
    
    shview = [[[NSBundle mainBundle] loadNibNamed:@"SHView" owner:nil options:nil] lastObject];
    shview.frame = CGRectMake(0, 0, ScreenWidth, 720);
    [sclview addSubview:shview];
    
    [shview.btnTJ addTarget:self action:@selector(clickTJ) forControlEvents:UIControlEventTouchUpInside];
    
    [shview.btn1 addTarget:self action:@selector(clicks1) forControlEvents:UIControlEventTouchUpInside];
    [shview.btn2 addTarget:self action:@selector(clicks2) forControlEvents:UIControlEventTouchUpInside];
    [shview.btn3 addTarget:self action:@selector(clicks3) forControlEvents:UIControlEventTouchUpInside];
    
    [shview.btnAgree addTarget:self action:@selector(clickAgree) forControlEvents:UIControlEventTouchUpInside];
    
    [shview.btnService addTarget:self action:@selector(clickService) forControlEvents:UIControlEventTouchUpInside];
    
    //区域选择
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click1)];
    shview.labSelPlace.userInteractionEnabled = YES;
    [shview.labSelPlace addGestureRecognizer:tap1];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click2:)];
    shview.image1.userInteractionEnabled = YES;
    shview.image1.tag = 1;
    [shview.image1 addGestureRecognizer:tap2];
    
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click2:)];
    shview.image2.userInteractionEnabled = YES;
    shview.image2.tag = 2;
    [shview.image2 addGestureRecognizer:tap3];
    
    UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click2:)];
    shview.image3.userInteractionEnabled = YES;
    shview.image3.tag = 3;
    [shview.image3 addGestureRecognizer:tap4];
    
    UITapGestureRecognizer *tap5 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click2:)];
    shview.image4.userInteractionEnabled = YES;
    shview.image4.tag = 4;
    [shview.image4 addGestureRecognizer:tap5];
    
}
//同意
- (void)clickAgree{
    if (shview.btnAgree.tag == 0) {
        [shview.btnAgree setImage:[UIImage imageNamed:@"勾-(1)"] forState:UIControlStateNormal];
        shview.btnAgree.tag = 1;
    }else{
        [shview.btnAgree setImage:[UIImage imageNamed:@"矩形-7"] forState:UIControlStateNormal];
        shview.btnAgree.tag = 0;
    }
}

- (void)clickService{
    if (![riView superview]) {
        riView = [[RigisterView alloc] init];
        [self.view addSubview:riView];
        [riView show];
    }
}

//费用选择
- (void)clicks1{
    [shview.btn1 setImage:[UIImage imageNamed:@"勾"] forState:UIControlStateNormal];
    [shview.btn2 setImage:[UIImage imageNamed:@"椭圆-2-拷贝"] forState:UIControlStateNormal];
    [shview.btn3 setImage:[UIImage imageNamed:@"椭圆-2-拷贝"] forState:UIControlStateNormal];
    _fyPrice = @"600";
}

- (void)clicks2{
    [shview.btn1 setImage:[UIImage imageNamed:@"椭圆-2-拷贝"] forState:UIControlStateNormal];
    [shview.btn2 setImage:[UIImage imageNamed:@"勾"] forState:UIControlStateNormal];
    [shview.btn3 setImage:[UIImage imageNamed:@"椭圆-2-拷贝"] forState:UIControlStateNormal];
    _fyPrice = @"800";
}

- (void)clicks3{
    [shview.btn1 setImage:[UIImage imageNamed:@"椭圆-2-拷贝"] forState:UIControlStateNormal];
    [shview.btn2 setImage:[UIImage imageNamed:@"椭圆-2-拷贝"] forState:UIControlStateNormal];
    [shview.btn3 setImage:[UIImage imageNamed:@"勾"] forState:UIControlStateNormal];
    _fyPrice = @"1200";
}

//区域选择
- (void)click1{
    bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight-250, ScreenWidth, 250)];
    bottomView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:bottomView];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(10, 0, 40, 40);
    [btn1 setTitle:@"取消" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(clickCancel) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:btn1];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(ScreenWidth-50, 0, 40, 40);
    [btn2 setTitle:@"确定" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(clickSure) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:btn2];
    
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, ScreenWidth, 210)];
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
    [bottomView addSubview:self.pickerView];
    
    bottomView.hidden = NO;
}

- (void)clickCancel{
    bottomView.hidden = YES;
}

- (void)clickSure{
    bottomView.hidden = YES;
}

- (void)click2:(id)sender{
    UITapGestureRecognizer *tap = (UITapGestureRecognizer *)sender;
    UIView *v = [tap view];
    if (v.tag == 1) {
        _imgState = @"1";
    }else if (v.tag == 2){
        _imgState = @"2";
    }else if (v.tag == 3){
        _imgState = @"3";
    }else{
        _imgState = @"4";
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册中获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}

//拍照获取
- (void)pickerPicture{
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        NSLog(@"用前置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagepc.delegate = self;
        imagepc.allowsEditing = YES;
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
    }else if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        NSLog(@"用后置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }else{
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"调用失败" message:@"请从手机相册中选择" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:a animated:YES completion:nil];
    }
    
    [self presentViewController:imagepc animated:YES completion:nil];
}

//从手机的图片获取
- (void)pickerPictureFromAlbum{
    UIImagePickerController *imgpicker = [[UIImagePickerController alloc] init];
    imgpicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgpicker.allowsEditing = YES;
    imgpicker.delegate = self;
    [self presentViewController:imgpicker animated:YES completion:nil];
    
}
#pragma -mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    if ([_imgState isEqualToString:@"1"]) {
        shview.image1.image = img;
    }else if ([_imgState isEqualToString:@"2"]){
        shview.image2.image = img;
    }else if ([_imgState isEqualToString:@"3"]){
        shview.image3.image = img;
    }else{
        shview.image4.image = img;
    }

    [self loadImage:img];
    [self dismissViewControllerAnimated:YES completion:nil];
}
//图片上传
- (void)loadImage:(UIImage *)image{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:@"pic.png" forKey:@"pic"];
    [parmas setObject:@"name" forKey:@"name"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/upload",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"pic" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:data name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *op = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSLog(@"dic:%@",op);
        NSString *error = [NSString stringWithFormat:@"%li",[[op objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            if ([_imgState isEqualToString:@"1"]) {
                _imgUrl1 = [op objectForKey:@"result"];
            }else if ([_imgState isEqualToString:@"2"]){
                _imgUrl2 = [op objectForKey:@"result"];
            }else if ([_imgState isEqualToString:@"3"]){
                _imgUrl3 = [op objectForKey:@"result"];
            }else{
                _imgUrl4 = [op objectForKey:@"result"];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

#pragma mark - PickerView Delegate
// 列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

// 每列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(component == 0){
        return self.regionArray.count;
    }
    else if (component == 1){
        return [self.regionArray[self.provinceIndex][@"citys"] count];
    }
    else{
        return [self.regionArray[self.provinceIndex][@"citys"][self.cityIndex][@"districts"] count];
    }
}
// 返回每一行的内容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(component == 0){
        return self.regionArray[row][@"province"];
    }
    else if (component == 1){
        return self.regionArray[self.provinceIndex][@"citys"][row][@"city"];
    }
    else{
        return self.regionArray[self.provinceIndex][@"citys"][self.cityIndex][@"districts"][row];
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

// 滑动或点击选择，确认pickerView选中结果
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if(component == 0){
        self.provinceIndex = row;
        self.cityIndex = 0;
        self.districtIndex = 0;
        
        [self.pickerView reloadComponent:1];
        [self.pickerView reloadComponent:2];
    }
    else if (component == 1){
        self.cityIndex = row;
        self.districtIndex = 0;
        
        [self.pickerView reloadComponent:2];
    }
    else{
        self.districtIndex = row;
    }
    [self resetPickerSelectRow];
}

-(void)resetPickerSelectRow
{
    [self.pickerView selectRow:self.provinceIndex inComponent:0 animated:YES];
    [self.pickerView selectRow:self.cityIndex inComponent:1 animated:YES];
    [self.pickerView selectRow:self.districtIndex inComponent:2 animated:YES];
    NSString *province = self.regionArray[self.provinceIndex][@"province"];
    NSString *city = self.regionArray[self.provinceIndex][@"citys"][self.cityIndex][@"city"];
    NSString *distric = self.regionArray[self.provinceIndex][@"citys"][self.cityIndex][@"districts"][self.districtIndex];
    NSString *address = [NSString stringWithFormat:@"%@-%@-%@", province, city, distric];
    NSLog(@"address:%@",address);
    shview.labSelPlace.text = address;
}




//呼叫上户
- (void)clickTJ{
    if (shview.text1.text.length == 0) {
        [self showAlert:@"请填写车辆品牌"];
        return;
    }else if (shview.text2.text.length == 0){
        [self showAlert:@"请填写车型"];
        return;
    }else if (shview.text3.text.length == 0){
        [self showAlert:@"请填写排量"];
        return;
    }else if ([self validateMobile:shview.text4.text] == 0){
        [self showAlert:@"请填写电话"];
        return;
    }else if ([shview.labSelPlace.text isEqualToString:@"请选择"]){
        [self showAlert:@"请选择地区"];
        return;
    }else if (_fyPrice.length == 0){
        [self showAlert:@"请选择上户费用"];
        return;
    }else if (_imgUrl1.length == 0){
        [self showAlert:@"请上传车辆发票图片"];
        return;
    }else if (_imgUrl2.length == 0){
        [self showAlert:@"请上传合格证图片"];
        return;
    }else if (_imgUrl3.length == 0){
        [self showAlert:@"请上传身份证正面照"];
        return;
    }else if (_imgUrl4.length == 0){
        [self showAlert:@"请上传身份证反面照"];
        return;
    }else if (shview.btnAgree.tag == 0){
        [self showAlert:@"请阅读并同意丫丢丢服务协议"];
        return;
    }
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:[user objectForKey:@"userid"] forKey:@"userid"];
    [parmas setObject:_orderNum forKey:@"ordernumber"];
    [parmas setObject:_merid forKey:@"merchantid"];
    [parmas setObject:_name forKey:@"ordername"];
    [parmas setObject:shview.text1.text forKey:@"brand"];
    [parmas setObject:shview.text2.text forKey:@"models"];
    [parmas setObject:shview.text3.text forKey:@"displacement"];
    [parmas setObject:shview.text4.text forKey:@"ownerphone"];
    [parmas setObject:shview.labSelPlace.text forKey:@"userarea"];
    [parmas setObject:_fyPrice forKey:@"ordermoney"];
    [parmas setObject:_imgUrl1 forKey:@"invoice"];
    [parmas setObject:_imgUrl2 forKey:@"certificate"];
    [parmas setObject:_imgUrl3 forKey:@"idcardone"];
    [parmas setObject:_imgUrl4 forKey:@"idcardtwo"];
    [parmas setObject:_lng forKey:@"longitude"];
    [parmas setObject:_lat forKey:@"latitude"];
    [parmas setObject:@"2" forKey:@"payment"];
    NSLog(@"parmas:%@",parmas);
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Onthedoor/onnobody",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"呼叫上户res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            [self alerts];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)alerts{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"提交成功，商家会尽快和您联系，如有疑问请拨打客服热线！" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

//生成订单号
- (void)loadNum{
    NSString *url = [NSString stringWithFormat:@"%@/App/Shoppingcart/ordernumber",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"res:%@",responseObject);
        _orderNum = [responseObject objectForKey:@"result"];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
